package com.jcj.endecoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.nio.ByteOrder;

/**
 * 客户端handler初始化配置类,在Channel注册到EventLoop后,对这个Channel添加一些初始化的Handler
 */
public class InitializerClientEnDeCoder extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        //定长解码器
       /* //消息接进来进入解码器(Decoder):这里列的顺序是:FixedLengthFrameDecoder-->StringDecoder-->HandlerClientFixedLength
        //消息发出去进入编码器(Encoder):这里列的顺序是:HandlerClientFixedLength-->StringEncoder
        ChannelPipeline pipeline =socketChannel.pipeline();
        //framer:是别名,可以自定义(处理拆包黏包的四大处理器都是帧处理器,所以这里取名为framer),定长解码器FixedLengthFrameDecoder
        pipeline.addLast("framer",new FixedLengthFrameDecoder(CommonTools.FIXEDLENGTHFRAME_LENGTH));
        pipeline.addLast("decoder",new StringDecoder());
        pipeline.addLast("encoder",new StringEncoder());
        //自定义业务逻辑handler
        pipeline.addLast(new HandlerClientFixedLength());*/


        //行解码器和分隔符解码器
        /*
             ChannelPipeline pipeline = socketChannel.pipeline();
            //行解码器:LineBasedFrameDecoder
            //pipeline.addLast("framer",new LineBasedFrameDecoder(CommonTools.LINEBASEDFRAME_LENGTH,true,true));
            //分隔符解码器:DelimiterBasedFrameDecoder
            ByteBuf delimiter=Unpooled.copiedBuffer("$".getBytes());
            pipeline.addLast("framer", new DelimiterBasedFrameDecoder(CommonTools.DELIMITERBASEDFRAME_LENGTH, true, true, delimiter));
            pipeline.addLast("decoder", new StringDecoder());
            pipeline.addLast("encoder", new StringEncoder());
            //自定义业务逻辑handler
            pipeline.addLast(new HandlerClientDelimiterBased());
         */

        ChannelPipeline pipeline = socketChannel.pipeline();
        //自定义长度解码器:LengthFieldBasedFrameDecoder
        pipeline.addLast("framer", new LengthFieldBasedFrameDecoder(2048, 3, 4, 0, 0));
        //自定义业务逻辑handler
        pipeline.addLast(new HandlerClientLengthFieldBased());

    }
}




















